package com.scce.Interceptor;

import com.scce.config.DynamicDataSourceHolder;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Locale;
import java.util.Properties;

@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class DynamicDataSourceInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceInterceptor.class);

    private static final String REGEX = ".*update\\u0020.*|.*insert\\u0020.*|.*delete\\u0020.*";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 首先判断是否是事务
        boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
        Object[] object = invocation.getArgs();
        MappedStatement ms = (MappedStatement) object[0];
        String lookUpkey = null;
        // 如果没有开启事务
        if (synchronizationActive != true) {
            if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
                // 如果是查询最后一条记录（select_last_record）,还是使用主库
                if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
                    lookUpkey = DynamicDataSourceHolder.DB_MASTER;
                } else {
                    lookUpkey = DynamicDataSourceHolder.DB_SLAVE;
                }
            } else {
                BoundSql boundSql = ms.getSqlSource().getBoundSql(object[1]);
                String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
                if (sql.matches(REGEX)) {
                    lookUpkey = DynamicDataSourceHolder.DB_MASTER;
                } else {
                    lookUpkey = DynamicDataSourceHolder.DB_SLAVE;
                }
            }
        } else {
            lookUpkey = DynamicDataSourceHolder.DB_MASTER;
        }
        logger.debug("设置方法[{}] use[{}] Strategy, SqlCommandType[{}]..", ms.getId(),
                lookUpkey, ms.getSqlCommandType().name());
        DynamicDataSourceHolder.setDbType(lookUpkey);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        // Executor表示增删改查的操作，如果存在增删改查的操作，将其拦截下来
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

